<template>
  <div>
    <el-card>
      <el-row class="row-custom">
        <el-col :span="24">
          <el-input type="textarea" v-model="compressData"
                    placeholder="请输入需要解压的数据，数据可以是json，也可以是gzip压缩后的纯文本"
                    :rows="10"></el-input>

          <el-input type="textarea" v-model="decompressData" placeholder="解压后数据" :rows="10"
                    class="row-custom"></el-input>
        </el-col>
      </el-row>
      <el-row class="row-custom">
        <el-col :span="24">
          <el-button type="success" @click="getClipboardData">一键粘贴</el-button>
          <el-button type="info" @click="resetData">重置</el-button>
          <el-button type="primary" @click="decompress">解压</el-button>
          <el-button type="danger" @click="copy2Clipboard">一键复制</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script setup>
import {ref} from 'vue'
import pako from 'pako';
import {ElMessage} from 'element-plus'

const compressData = ref('')
const decompressData = ref('')

const decompress = () => {
  let data = compressData.value
  if (!data) {
    ElMessage({
      message: '请输入需要解压的数据',
      type: 'warning',
    })
    return
  }
  if (isJSON(data)) {
    console.log('data is json');
    const dataObj = JSON.parse(data);
    if (dataObj.data) {
      data = dataObj.data;
    }
  }
  try {
    let strings = data.split(',');
    let inflate = pako.inflate(strings, {to: 'string'});
    decompressData.value = inflate
  } catch (e) {
    ElMessage({
      message: '解压数据发生异常，请检查数据是否正确.' + e,
      type: 'error',
    })
  }
}

const copy2Clipboard = () => {
  if (!decompressData.value) {
    ElMessage({
      message: '解压后数据为空，无法复制',
      type: 'warning',
    })
    return
  }
  navigator.clipboard.writeText(decompressData.value)
      .then(() => {
        ElMessage({
          message: '文本已复制到剪贴板',
          type: 'success',
        })
      })
      .catch(err => {
        // 复制失败后的操作
        console.error('复制失败:', err);
        ElMessage({
          message: '复制失败',
          type: 'error',
        })
      });
}

const getClipboardData = () => {
  navigator.clipboard.readText()
      .then(text => {
        compressData.value = text
      })
      .catch(err => {
        console.error('粘贴失败:', err);
        ElMessage({
          message: '粘贴失败',
          type: 'error',
        })
      });
}

const isJSON = (jsonStr) => {
  try {
    JSON.parse(jsonStr);
    return true;
  } catch (e) {
    return false;
  }
}

const resetData = () => {
  compressData.value = ''
  decompressData.value = ''
}

</script>

<style scoped lang="scss">
.row-custom {
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>
